package com.ctg.itrdc.imageconsole.common.util;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zookeeper.ZooKeeper;

/**
 * ZK操作工具类
 * @author wupiao
 *
 */
public class ZkUtils implements Watcher {

	private static final Logger logger = LoggerFactory.getLogger(ZkUtils.class);
	
	private ZooKeeper zk = null;

	private CountDownLatch connectedSemaphore = new CountDownLatch(1);

	/**
	 * 创建ZK连接
	 * 
	 * @param connectString
	 *            ZK服务器地址列表
	 * @param sessionTimeout
	 *            Session超时时间
	 */
	public void createConnection(String connectString, int sessionTimeout) {
		this.releaseConnection();
		try {
			zk = new ZooKeeper(connectString, sessionTimeout, this);
			connectedSemaphore.await();
		} catch (InterruptedException e) {
			logger.error("连接创建失败，发生 InterruptedException",e);
		} catch (IOException e) {
			logger.error("连接创建失败，发生 IOException",e);
		}
	}

	/**
	 * 关闭ZK连接
	 */
	public void releaseConnection() {
		if (null != this.zk) {
			try {
				this.zk.close();
			} catch (InterruptedException e) {
				logger.error("关闭ZK连接时，发生 InterruptedException",e);
			}
		}
	}

	/**
	 * 创建节点
	 * 
	 * @param path
	 *            节点path
	 * @param data
	 *            初始数据内容
	 * @return
	 */
	public boolean createPath(String path, String data) {
		try {
			System.out.println("节点创建成功, Path: " + this.zk.create(path, //
					data.getBytes(), //
					Ids.OPEN_ACL_UNSAFE, //
					CreateMode.EPHEMERAL) + ", content: " + data);
		} catch (KeeperException e) {
			logger.error("节点创建失败，发生KeeperException",e);
		} catch (InterruptedException e) {
			logger.error("节点创建失败，发生 InterruptedException",e);
		}
		return true;
	}

	/**
	 * 读取指定节点数据内容
	 * 
	 * @param path
	 *            节点path
	 * @return
	 */
	public String readData(String path) {
		try {
			return new String(this.zk.getData(path, false, null));
		} catch (KeeperException e) {
			logger.error("读取数据失败，发生KeeperException",e);
			return "";
		} catch (InterruptedException e) {
			logger.error("读取数据失败，发生 InterruptedException",e);
			return "";
		}
	}
	
	public List<String> getChildNodes(String path) {
		try {
			return this.zk.getChildren(path, false);
		} catch (KeeperException e) {
			logger.error("获取节点列表失败，发生KeeperException",e);
			return null;
		} catch (InterruptedException e) {
			logger.error("获取节点列表失败，发生InterruptedException",e);
			return null;
		}
	}

	
	
	/**
	 * 收到来自Server的Watcher通知后的处理。
	 */
	@Override
	public void process(WatchedEvent event) {
		System.out.println("收到事件通知：" + event.getState() + "\n");
		if (KeeperState.SyncConnected == event.getState()) {
			connectedSemaphore.countDown();
		}

	}

	public static void main(String[] args) {
		String ZK_PATH = "/alogic/global/arm";

		ZkUtils zkUtils = new ZkUtils();
		zkUtils.createConnection("10.142.90.21:8181", 10000);
		
		List<String> nodes = zkUtils.getChildNodes(ZK_PATH);
		for(String node:nodes){
			List<String> leafNode = zkUtils.getChildNodes(ZK_PATH+"/"+node);
			if (leafNode.size()>0) {
				System.out.println(leafNode);
			}
		}

		zkUtils.releaseConnection();
	}

	

}